import React, { memo, useState, useEffect } from 'react';
import _ from 'lodash';
import { Button, Drawer, Tabs, Spin, Checkbox, Row, Col, Empty, message } from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import DebounceWrapper from '@/components/DebounceWrapper';
import { fetchResourceMenuActionItems } from '@/services/system/resource';
import {
  fetchResourceButtonAuthByRoleId,
  updateResourceButtonAuthByRoleId,
} from '@/services/system/role';
import styles from './grainedAuthDrawer.less';

const DebounceButton = DebounceWrapper(Button);

const ButtonAuthTab = memo(
  ({ roleId, resourceId, actionLoading, setActionLoading }) => {
    const [buttonAuthList, setButtonAuthList] = useState([]);
    const [buttonAuthChecked, setButtonAuthChecked] = useState([]);
    const [initialLoading, setInitialLoading] = useState(true);

    // 获取菜单下的按钮/接口配置
    const getResourceActionData = async () => {
      try {
        const res = await fetchResourceMenuActionItems({ resourceId });
        return _.isArray(res) ? _.filter(res, ({ id }) => !!id) : [];
      } catch (e) {
        return [];
      }
    };
    // 获取角色已授权的的按钮/接口列表
    const getActionAuthKeyByRole = async () => {
      try {
        const res = await fetchResourceButtonAuthByRoleId({ roleId, resourceId });
        return _.isArray(res) ? res : [];
      } catch (e) {
        return [];
      }
    };

    // 初始化
    useEffect(() => {
      Promise.all([getResourceActionData(), getActionAuthKeyByRole()]).then((result) => {
        const [list, checkedKeys] = result;
        // 剔除无效的授权id列表
        const validCheckedIds = _.map(
          _.filter(list, ({ componentKey }) => _.includes(checkedKeys, componentKey)),
          'id',
        );
        // 数据更新
        setButtonAuthList(list);
        setButtonAuthChecked(validCheckedIds);
        setInitialLoading(false);
      });
    }, []);

    // 提交
    const handleConfirm = () => {
      setActionLoading(true);
      const params = { roleId, resourceId, resIds: buttonAuthChecked };
      // console.log('params', params);
      updateResourceButtonAuthByRoleId(params)
        .then(() => {
          setActionLoading(false);
          message.success('按钮/接口授权成功');
        })
        .catch(() => {
          setActionLoading(false);
        });
    };

    return (
      <Spin spinning={initialLoading} tip={'初始化..'}>
        {buttonAuthList.length ? (
          <>
            <Checkbox.Group
              value={buttonAuthChecked}
              className={styles.authButtonContainer}
              onChange={(values) => {
                setButtonAuthChecked(values);
              }}
            >
              <Row>
                {buttonAuthList.map((item) => (
                  <Col span={24} key={item.id}>
                    <Checkbox value={item.id}>{item.componentName}</Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
            <DebounceButton
              size="small"
              type="primary"
              icon={<SaveOutlined />}
              loading={actionLoading}
              onClick={handleConfirm}
            >
              保存
            </DebounceButton>
          </>
        ) : (
          <Empty description="暂无数据.." />
        )}
      </Spin>
    );
  },
  (prevProps, nextProps) => prevProps.actionLoading === nextProps.actionLoading,
);

// TODO 数据规则授权待开发
const DataAuthTab = memo(
  ({ roleId, resourceId, actionLoading, setActionLoading }) => {
    const [dataAuthList, setDataAuthList] = useState([]);
    const [dataAuthChecked, setDataAuthChecked] = useState([]);
    const [dataAuthInitialLoadingId, setDataAuthInitialLoadingId] = useState('');

    return (
      <div>
        <span>数据规则操作(待接入业务后二次开发)</span>
      </div>
    );
  },
  (prevProps, nextProps) => prevProps.actionLoading === nextProps.actionLoading,
);

export default ({ visible, roleId, resourceId, resourceName, closeDrawer }) => {
  const [activeTabKey, setActiveTabKey] = useState('authButton');
  const [buttonAuthActionLoading, setButtonAuthActionLoading] = useState(false);
  const [dataAuthActionLoading, setDataAuthActionLoading] = useState(false);

  const handleCancel = () => {
    if (!(buttonAuthActionLoading || dataAuthActionLoading)) {
      closeDrawer();
    }
  };

  useEffect(() => {
    if (!visible) {
      setActiveTabKey('authButton');
    }
  }, [visible]);

  return (
    <Drawer
      destroyOnClose
      visible={visible}
      title={`细粒度资源授权${resourceName ? '（' + resourceName + '）' : ''}`}
      onClose={handleCancel}
    >
      <Tabs
        activeKey={activeTabKey}
        onChange={(nextKey) => {
          if (!(buttonAuthActionLoading || dataAuthActionLoading)) {
            setActiveTabKey(nextKey);
          }
        }}
      >
        <Tabs.TabPane tab="按钮/接口授权" key="authButton">
          <ButtonAuthTab
            roleId={roleId}
            resourceId={resourceId}
            actionLoading={buttonAuthActionLoading}
            setActionLoading={setButtonAuthActionLoading}
          />
        </Tabs.TabPane>
        <Tabs.TabPane tab="数据规则授权" key="authData">
          <DataAuthTab
            roleId={roleId}
            resourceId={resourceId}
            actionLoading={dataAuthActionLoading}
            setActionLoading={setDataAuthActionLoading}
          />
        </Tabs.TabPane>
      </Tabs>
    </Drawer>
  );
};
